package com.twetec.cms.adapter.pc.backend.controller.website;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.twetec.cms.adapter.pc.backend.annotion.SitePermission;
import com.twetec.cms.adapter.pc.backend.response.R;
import com.twetec.cms.adapter.pc.backend.response.ResultCodeMsgEnum;
import com.twetec.cms.adapter.pc.backend.tag.doc.TagDocManager;
import com.twetec.cms.adapter.pc.backend.tag.doc.TagDocObject;
import com.twetec.cms.common.constant.ArticleEnum;
import com.twetec.cms.common.constant.CmsSiteTemplatePermissionEnum;
import com.twetec.cms.common.constant.ColumnEnum;
import com.twetec.cms.common.constant.FileConst;
import com.twetec.cms.common.util.validate.ValidateUtil;
import com.twetec.cms.model.po.user.UserPO;
import com.twetec.cms.model.po.website.WebsiteTemplatePO;
import com.twetec.cms.model.vo.website.*;
import com.twetec.cms.service.file.LocalFileService;
import com.twetec.cms.service.ucenter.UserService;
import com.twetec.cms.service.website.WebsiteTemplateService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Api(tags = "模板管理")
@RestController
@RequestMapping("/website/template")
public class TemplateController {
    @Autowired
    WebsiteTemplateService templateService;

    @Autowired
    UserService userService;

    /**
     * 资源文件根目录
     */
    @Value("${twetec.resource.storage-root-path}")
    private String resourceStorageRootPath;

    @Autowired
    LocalFileService localFileService;

    private static final String TEMPLATE_PAGE = "template:page-search-list-by-site-id";
    private static final String CREATE = "template:create";
    private static final String TEMPLATE_DETAIL = "template:get-by-id";
    private static final String UPDATE_BY_ID = "template:update-by-id";
    private static final String SET_USE_BY_ID = "template:set-use-by-id";
    private static final String DELETE = "template:delete-template-by-templateId";
    private static final String DEVELOP = "template:develop";
    private static final String BATCH_DELETE = "template:batch-delete";


    @SitePermission({TEMPLATE_PAGE})
    @ApiOperation(value = "模板分页列表展示与搜索", notes = "模板分页列表展示与搜索")
    @GetMapping("/page-search-list-by-site-id")
    public R<TemplatePageListVO> pageSearchListBySiteId(@ApiParam(value = "站点id", required = true, example = "123456789") @RequestParam(required = false) Long siteId,
                                    @ApiParam(value = "模板名称", required = false, example = "h5模板名称") @RequestParam(required = false) String name,
                                    @ApiParam(value = "是否使用(0未使用,1使用)", required = false, example = "1") @RequestParam(required = false) String use,
                                    @ApiParam(value = "模板编码(小写英文字母和下划线组成)", required = false, example = "wzmx") @RequestParam(required = false) String code,
                                    @ApiParam(value = "模板类型", required = false, example = "H5或PC") @RequestParam(required = false) String type,
                                    @ApiParam(value = "备注信息", required = false, example = "这是文章模板的备注") @RequestParam(required = false) String remark,
                                    @ApiParam(value = "更新人", required = false, example = "张三") @RequestParam(required = false) String modifierName,
                                    @ApiParam(value = "根据更新时间搜索的开始时间（10位时间戳）", required = false, example = "1234567891") @RequestParam(required = false) Date gmtModifiedStart,
                                    @ApiParam(value = "根据更新时间搜索的结束时间（10位时间戳）", required = false, example = "1231231231") @RequestParam(required = false) Date gmtModifiedEnd,
                                    @ApiParam(value = "要访问的页码", required = true, example = "1") @RequestParam(required = false) Integer page,
                                    @ApiParam(value = "页面容量", required = true, example = "10") @RequestParam(required = false) Integer limit) {

        // 站点id
        if (null == siteId || !ValidateUtil.Number(siteId) || siteId < 0) return R.failure().msg("站点id格式不正确");

        // 模板编码 TODO::模板编码重写方法
        if (code != null && code.length() > 50) return R.failureRequestParam().msg("模板编码超过50个字符");

        // 页面
        if (null == page || !ValidateUtil.Number(page) || page < 0)
            return R.failureRequestParam().msg("要访问的页码为空或格式不正确");
        if (null == limit || !ValidateUtil.Number(limit) || limit < 0)
            return R.failureRequestParam().msg("页面容量为空或格式不正确");


        // 设置返回数据
        TemplatePageListVO templatePageListVO = new TemplatePageListVO();

        // 设置查询条件
        QueryWrapper<WebsiteTemplatePO> templatePOQueryWrapper = new QueryWrapper<>();
        // 站点id
        templatePOQueryWrapper.eq("SITE_ID", siteId);
        // 模板名称
        if (StringUtils.isNotEmpty(name) && name.length() < 100) templatePOQueryWrapper.like("NAME", name);
        // 是否使用
        if (StringUtils.isNotEmpty(use) && ValidateUtil.Number(use)) templatePOQueryWrapper.eq("IS_USE", use);
        // 模板编码
        if (StringUtils.isNotEmpty(code) && code.length() <= 50) templatePOQueryWrapper.like("CODE", code);
        // 模板类型
        if (StringUtils.isNotEmpty(type) && type.length() < 10) templatePOQueryWrapper.like("TYPE", type);
        // 备注信息
        if (StringUtils.isNotEmpty(remark) && remark.length() <= 255) templatePOQueryWrapper.like("REMARK", remark);

        // 根据更新人name查询更新人id
        List<UserPO> userPOList = null;
        if (StringUtils.isNotEmpty(modifierName)) {
            QueryWrapper<UserPO> userWrapper = new QueryWrapper<>();
            // userPOQueryWrapper1.select("ID");
            userWrapper.like("NAME", modifierName);
            userPOList = userService.list(userWrapper);
        }

        // 获取更新人ID的集合
        if (userPOList != null && userPOList.size() > 0) {
            ArrayList<Long> userIdList = new ArrayList<>();
            for (UserPO userPO : userPOList) {
                userIdList.add(userPO.getId());
            }

            // 添加到查询条件
            templatePOQueryWrapper.in("MODIFIER_ID", userIdList);
        }
        // 当更新人id查询结果为空，但是传入的更新人姓名不为空的时候，表示表中没有对应的操作人，直接返回空集合
        if ((userPOList == null || userPOList.size() == 0) && StringUtils.isNotEmpty(modifierName)) {
            templatePageListVO.setPage(page);
            templatePageListVO.setLimit(limit);
            templatePageListVO.setTotal(0);
            templatePageListVO.setList(new ArrayList<>());
            return R.success().data(templatePageListVO);
        }

        // 更新时间
        if (null != gmtModifiedStart) {
            templatePOQueryWrapper.ge("GMT_MODIFIED", gmtModifiedStart);
        }
        if (null != gmtModifiedEnd) {
            templatePOQueryWrapper.le("GMT_MODIFIED", gmtModifiedEnd);
        }

        // 排序
        templatePOQueryWrapper.orderByDesc("GMT_MODIFIED");

        // 执行查询
        Page<WebsiteTemplatePO> templatePOPage = templateService.page(new Page<>(page, limit), templatePOQueryWrapper);

        templatePageListVO.setTotal((int) templatePOPage.getTotal());
        templatePageListVO.setPage((int) templatePOPage.getCurrent());
        templatePageListVO.setLimit((int) templatePOPage.getSize());

        // 获取查询到的模板记录
        List<WebsiteTemplatePO> records = templatePOPage.getRecords();

        ArrayList<TemplateVO> templateList = new ArrayList<>();
        // 遍历模板记录，复制属性到VO并添加更新人名字
        for (WebsiteTemplatePO templatePO : records) {
            TemplateVO templateVO = new TemplateVO();
            BeanUtils.copyProperties(templatePO, templateVO);
            QueryWrapper<UserPO> modifierWrapper = new QueryWrapper<>();
            modifierWrapper.eq("ID", templatePO.getModifierId());
            UserPO modifierPO = userService.getOne(modifierWrapper);
            if (modifierPO != null) templateVO.setModifierName(modifierPO.getName());
            templateList.add(templateVO);
        }
        templatePageListVO.setList(templateList);

        return R.success().data(templatePageListVO);
    }

    @SitePermission(CREATE)
    @ApiOperation(value = "新增模板", notes = "新增模板")
    @PostMapping("/create")
    public R create(@ApiParam(value = "站点id", required = true, example = "123456789") @RequestParam(required = false) Long siteId,
                    @ApiParam(value = "模板名称", required = true, example = "h5模板名称") @RequestParam(required = false) String name,
                    @ApiParam(value = "模板编码(小写英文字母和下划线组成)", required = true, example = "wzmx") @RequestParam(required = false) String code,
                    @ApiParam(value = "模板类型(H5或PC)", required = true, example = "PC") @RequestParam(required = false) String type,
                    @ApiParam(value = "备注信息", required = false, example = "这段话是文章模板的备注...") @RequestParam(required = false) String remark,
                    @RequestAttribute("userId") Long userId) {



        // 站点id
        if (null == siteId || !ValidateUtil.Number(siteId) || siteId < 0)
            return R.failureRequestParam().msg("站点id格式不正确");
        // 模板名称
        if (null == name || name.length() > 100) return R.failureRequestParam().msg("模板名称不能为空且长度小于100");
        // 模板编码
        if (null == code || code.length() > 50 || code.length() <= 0)
            return R.failureRequestParam().msg("模板编码不能为空且长度小于50");
        Boolean codeResult = templateService.checkTemplateCode(siteId, null, code);
        if (!codeResult) return R.failure().msg("模板编码重复");
        // 模板类型
        if (StringUtils.isEmpty(type) || (!type.equals("H5") && !type.equals("PC")))
            return R.failureRequestParam().msg("模板类型为空或不正确");

        // 备注
        if (remark != null && remark.length() > 255) return R.failureRequestParam().msg("模板备注长度要小于255");

        WebsiteTemplatePO templatePO = new WebsiteTemplatePO();
        templatePO.setCode(code);
        templatePO.setName(name);
        templatePO.setSiteId(siteId);
        templatePO.setType(type);
        templatePO.setRemark(remark);
        templatePO.setCreatorId(userId);
        templatePO.setModifierId(userId);
        boolean result = templateService.save(templatePO);
        if (result) return R.success().msg("添加成功");
        return R.failure().msg("添加失败");
    }

    @SitePermission({TEMPLATE_DETAIL})
    @ApiOperation(value = "根据模板id获取模板信息", notes = "根据模板id获取模板信息")
    @GetMapping("/get-by-id")
    public R<TemplateItemVO> getById(@ApiParam(value = "id", required = true, example = "12312313123") @RequestParam(required = false) Long id) {

        // 校验id
        if (null == id || !ValidateUtil.Number(id) || id <= 0) return R.failureRequestParam().msg("模板id输入有误");

        WebsiteTemplatePO templatePO = null;
        templatePO = templateService.getById(id);

        // 如果为空，则提示数据不存在
        if (templatePO == null) return R.resultCodeMsg(ResultCodeMsgEnum.DATA_NOT_EXIST);

        // 如果不为空，则再正常返回
        TemplateItemVO templateItemVO = new TemplateItemVO();
        BeanUtils.copyProperties(templatePO, templateItemVO);

        return R.success().data(templateItemVO);
    }

    @SitePermission({UPDATE_BY_ID})
    @ApiOperation(value = "根据模板id修改模板信息", notes = "根据模板id修改模板信息")
    @PutMapping("/update-by-id")
    public R updateById(@ApiParam(value = "id", required = true, example = "12312313123") @RequestParam(required = false) Long id,
                        @ApiParam(value = "模板名称", required = true, example = "h5模板名称") @RequestParam(required = false) String name,
                        @ApiParam(value = "模板编码(小写英文字母和下划线组成)", required = true, example = "wzmx") @RequestParam(required = false) String code,
                        @ApiParam(value = "模板类型(H5或PC)", required = true, example = "PC") @RequestParam(required = false) String type,
                        @ApiParam(value = "备注信息", required = false, example = "这是文章模板的备注") @RequestParam(required = false) String remark) {

        // 校验id
        if (null == id || !ValidateUtil.Number(id) || id <= 0) return R.failureRequestParam().msg("模板id输入有误");
        // 模板名称
        if (null == name || name.length() > 100) return R.failureRequestParam().msg("模板名称不能为空且长度小于100");
        // 模板编码
        if (null == code || code.length() > 50 || code.length() <= 0)
            return R.failureRequestParam().msg("模板编码不能为空且长度小于50");

        WebsiteTemplatePO templatePOById = templateService.getById(id);
        Boolean codeResult = templateService.checkTemplateCode(templatePOById.getSiteId(), id, code);
        if (!codeResult) return R.failure().msg("模板编码重复");
        // 模板类型
        if (StringUtils.isEmpty(type) || (!type.equals("H5") && !type.equals("PC")))
            return R.failureRequestParam().msg("模板类型为空或不正确");
        // 备注
        if (remark != null && remark.length() > 255) return R.failureRequestParam().msg("模板备注长度要小于255");
        // 执行修改操作
        WebsiteTemplatePO templatePO = new WebsiteTemplatePO();
        templatePO.setId(id);
        templatePO.setName(name);
        templatePO.setCode(code);
        templatePO.setType(type);
        templatePO.setRemark(remark);

        boolean result = templateService.updateById(templatePO);
        if (result) return R.success().msg("根据模板id修改模板信息成功");
        return R.failure().msg("根据模板id修改模板信息失败");

    }

    @SitePermission({SET_USE_BY_ID})
    @ApiOperation(value = "根据模板id设置当前使用", notes = "根据模板id设置当前使用")
    @PutMapping("/set-use-by-id")
    public R setUseById(@ApiParam(value = "id", required = true, example = "12312313123") @RequestParam(required = false) Long id,
                        @RequestAttribute("userId") Long userId) {

        // 校验id
        if (null == id || !ValidateUtil.Number(id) || id <= 0) return R.failureRequestParam().msg("模板id输入有误");

        WebsiteTemplatePO templatePOById = templateService.getById(id);
        if(null == templatePOById) return R.resultCodeMsg(ResultCodeMsgEnum.DATA_NOT_EXIST);

        // 设置该站点下该类型的模板的is_use为0
        QueryWrapper<WebsiteTemplatePO> websiteTemplatePOQueryWrapper = new QueryWrapper<>();
        websiteTemplatePOQueryWrapper.eq("SITE_ID", templatePOById.getSiteId());
        websiteTemplatePOQueryWrapper.eq("TYPE", templatePOById.getType());

        WebsiteTemplatePO updateTemplatePO = new WebsiteTemplatePO();
        updateTemplatePO.setUse("0");
        templateService.update(updateTemplatePO, websiteTemplatePOQueryWrapper);

        // 修改当前模板的的IS_USE
        WebsiteTemplatePO templatePO = new WebsiteTemplatePO();
        templatePO.setId(id);
        templatePO.setUse("1");
        templatePO.setModifierId(userId);

        boolean result = templateService.updateById(templatePO);
        if (result) return R.success().msg("操作成功");
        return R.failure().msg("操作失败");
    }


    @SitePermission({DEVELOP})
    @ApiOperation(value = "根据模板id加载模板树", notes = "根据模板id加载模板树")
    @GetMapping("/load-template-tree-by-id")
    public R<TemplateTreeListVO> loadTemplateTreeById(@ApiParam(value = "id", required = true, example = "12312313123") @RequestParam(required = false) Long id) {

        // 校验id
        if (null == id || !ValidateUtil.Number(id) || id <= 0) return R.failureRequestParam().msg("模板id输入有误");
        TemplateTreeListVO templateTreeListVO = localFileService.getFileTreeListByTemplateId(id);

        return R.success().data(templateTreeListVO);
    }

    @ApiOperation(value = "模板树新增目录", notes = "模板树新增目录")
    @PostMapping("/create-file-dir")
    public R createFileDir(@ApiParam(value = "目录名称（目录名称只能由小写字母和下划线组成）", required = true, example = "dir__") @RequestParam(required = false) String dirName,
                           @ApiParam(value = "当前所在路径", required = true, example = "D:\\dir_sdf") @RequestParam(required = false) String path) {

        // 校验目录名称
        if (null == dirName) return R.failureRequestParam().msg("目录名称不能为空");
        // 校验当前所在路径
        if (null == path) return R.failureRequestParam().msg("当前所在路径不能为空");
        if (!ValidateUtil.LetterINumber(dirName)) return R.failureRequestParam().msg("目录名称只能由小写字母和下划线组成");

        boolean templateDir = localFileService.createTemplateDir(path, dirName);

        return templateDir ? R.success() : R.failure().msg("目录已存在");
    }


    @ApiOperation(value = "模板树新增文件", notes = "模板树新增文件")
    @PostMapping("/create-file")
    public R createFile(@ApiParam(value = "文件名称（文件名称只能为小写字母和下划线）", required = true, example = "sld_ak") @RequestParam(required = false) String fileName,
                        @ApiParam(value = "当前所在路径", required = true, example = "D:\\filedsklg") @RequestParam(required = false) String path) {

        // 校验目录名称
        if (null == fileName) return R.failureRequestParam().msg("文件名称不能为空");

        if (!ValidateUtil.LetterINumber(fileName)) return R.failureRequestParam().msg("文件名称只能为小写字母和下划线");

        // 校验当前所在路径
        if (null == path) return R.failureRequestParam().msg("当前所在路径不能为空");
        boolean result = localFileService.createTemplateFile(path, fileName);

        return result ? R.success() : R.failure().msg("目录已存在");

    }

    @ApiOperation(value = "模板导入文件", notes = "模板导入文件")
    @PostMapping("/import-file")
    public R importFile(@ApiParam(value = "file", required = true, example = "importfile") @RequestParam(required = false) MultipartFile file,
                        @ApiParam(value = "当前所在路径", required = true, example = "D:\\importfile.html") @RequestParam(required = false) String path) {

        // 校验上传文件是否为空
        if (null == file) return R.failureRequestParam().msg("请选择要导入的文件");

        // 校验文件的大小 上传文件最大值 100M
        if (file.getSize() > FileConst.UPLOAD_FILE_MAX_SIZE) return R.failureRequestParam().msg("文件大小不能超过" + FileConst.UPLOAD_FILE_MAX_SIZE + "M");

        String fileName = file.getOriginalFilename();
//        if (!FileUtil.getSuffix(fileName).equals("html")) return R.failureRequestParam().msg("请传入html类型的文件");

        if (FileUtil.exist(path + File.separator + fileName)) return R.failure().msg("文件名重复");

        boolean result = false;
        try {
            result = localFileService.uploadFileContent(path, file);
        } catch (IOException e) {
            e.printStackTrace();
            return R.failure().msg(e.getMessage());
        }

        return result ? R.success() : R.failure();
    }

    @ApiOperation(value = "模板读取指定文件", notes = "模板读取指定文件")
    @GetMapping("/get-file-content")
    public R<FileContentVO> getFileContent(@ApiParam(value = "完整的路径", required = true, example = "D:\\file.html") @RequestParam(required = false) String path) {

        // 校验完整的路径
        if (null == path) return R.failureRequestParam().msg("路径不能为空");

        if (!FileUtil.exist(path)) return R.failure().msg("模板文件不存在");
        FileContentVO fileContentVO = new FileContentVO();
        String fileContentString = new String();
        try {
            StringBuffer fileContent = localFileService.getFileContent(path);
            fileContentString = fileContent.toString();
            fileContentVO.setContent(fileContentString);
        } catch (IOException e) {
            e.printStackTrace();
            return R.failure();
        }

        return R.success().data(fileContentVO);
    }

    @ApiOperation(value = "模板修改指定文件", notes = "模板修改指定文件")
    @PutMapping("/set-file-content")
    public R setFileContent(@ApiParam(value = "完整的路径", required = true, example = "D:\\file.html") @RequestParam(required = false) String path,
                            @ApiParam(value = "模板文件内容", required = false, example = "hhhhhhh") @RequestParam(required = false) String content) {

        // 校验完整的路径
        if (null == path) return R.failureRequestParam().msg("路径不能为空");

        if (!FileUtil.exist(path)) return R.failure().msg("模板文件不存在");

        if (!FileUtil.isFile(path)) return R.failure().msg("路径指向的不是文件");

        boolean result = false;
        try {
            result = localFileService.setFileContent(path, content);
        } catch (IOException e) {
            e.printStackTrace();
            return R.failure().msg(e.getMessage());
        }

        return result ? R.success().msg("修改成功") : R.failure();
    }


    @ApiOperation(value = "模板下载指定文件", notes = "模板下载指定文件")
    @GetMapping("/download-file")
    public R downloadFile(@ApiParam(value = "完整的路径", required = true, example = "D:\\") @RequestParam(required = false) String path,
                          HttpServletResponse response) {
        // 校验路径
        if (null == path) return R.failureRequestParam().msg("路径不能为空");

        // 新建文件对象与验证
        File file = FileUtil.file(path);
        if (!file.exists()) return R.failureRequestParam().msg("路径不存在");

        try {
            File downloadFileContent = localFileService.downloadFileContent(path, response);
        } catch (IOException e) {
            e.printStackTrace();
            return  R.failure().msg(e.getMessage());
        }

        return R.success();
    }


    @ApiOperation(value = "模板编码数据校验", notes = "模板编码数据校验")
    @GetMapping("/code-data-check")
    public R encodedDataCheck(@ApiParam(value = "站点id", required = true, example = "1435204946847760385") @RequestParam(required = false) Long siteId,
                              @ApiParam(value = "当前模板id（若是新建模板就不传，若是更新就传）", required = false, example = "123456789111") @RequestParam(required = false) Long templateId,
                              @ApiParam(value = "模板编码", required = true, example = "hhhh,") @RequestParam(required = false) String code) {

//        // 站点id
//        if (null == siteId || !ValidateUtil.Number(siteId) || siteId < 0) return R.failureRequestParam().msg("站点id格式不正确");
//        // 当前模板的id
//        if (templateId != null && ValidateUtil.Number(templateId) && templateId < 0) return R.failureRequestParam().msg("当前模板的id格式不正确");
//        // 模板编码
//        if (StringUtils.isEmpty(code)) return R.failureRequestParam().msg("模板编码为空");
//
////        Long userId = 1371387567439171585L;
//
//        Boolean result = templateService.checkTemplateCode(siteId, templateId, code);
//        if (result)
            return R.success();
//        return R.failure().msg("模板编码重复");
    }


    @ApiOperation(value = "删除模板树目录", notes = "删除模板树目录")
    @DeleteMapping("/delete-file-dir")
    public R deleteFileDir(@ApiParam(value = "完整的路径", required = true, example = "D:\\") @RequestParam(required = false) String path) {

        // 校验路径
        if (null == path) return R.failureRequestParam().msg("路径不能为空");

        File file = FileUtil.file(path);
//        if (!FileUtil.exist(path)) return R.failureRequestParam().msg("目录不存在");
        if (!FileUtil.isDirEmpty(file)) {
            return R.failure().msg("目录不为空");
        }

        boolean result = localFileService.deleteTemplateDir(path);

        return result ? R.success() :R.failure();
    }

    @ApiOperation(value = "删除模板树文件", notes = "删除模板树文件")
    @DeleteMapping("/delete-file")
    public R deleteFile(@ApiParam(value = "完整的路径", required = true, example = "D:\\") @RequestParam(required = false) String path) {

        // 校验路径
        if (null == path) return R.failureRequestParam().msg("路径不能为空");

        File file = FileUtil.file(path);
        if (!FileUtil.exist(path)) return R.failureRequestParam().msg("文件不存在");
        String fileName = file.getName();
        String parentDir = file.getParent();

        boolean result = localFileService.deleteTemplateFile(path);

        return result ? R.success() : R.failure();
    }

    @ApiOperation(value = "获取模板标签", notes = "获取模板标签")
    @GetMapping("/get-template-tag")
    public R<TemplateTagListVO> getTemplateTag() {

        // 返回值
        TemplateTagListVO templateTagListVO = new TemplateTagListVO();
        ArrayList<TemplateTagItemVO> templateTagItemVOArrayList = new ArrayList<>();

        List<TagDocObject> tagDocObjectList = TagDocManager.docList();
        for (TagDocObject tagDocObject : tagDocObjectList) {
            TemplateTagItemVO templateTagItemVO = new TemplateTagItemVO();
            BeanUtils.copyProperties(tagDocObject, templateTagItemVO);
            templateTagItemVOArrayList.add(templateTagItemVO);
        }

        templateTagListVO.setList(templateTagItemVOArrayList);
        return R.success().data(templateTagListVO);

    }

    @ApiOperation(value = "根据站点id获取默认PC模板", notes = "根据站点id获取默认PC模板")
    @GetMapping("/load-pc-template-tree-by-site-id")
    public R<HtmlTemplateTreeListVO> loadPCTemplateTreeBySiteId(@ApiParam(value = "站点id", required = true, example = "12312313123") @RequestParam(required = false) Long siteId) {


        // 校验id
        if (null == siteId || !ValidateUtil.Number(siteId) || siteId <= 0) return R.failureRequestParam().msg("站点id输入有误");

        // 返回值
        HtmlTemplateTreeListVO templateTreeListVO = new HtmlTemplateTreeListVO();

        // 根据站点id 查询pc类型的并且被是被使用的模板
        QueryWrapper<WebsiteTemplatePO> templatePOQueryWrapper = new QueryWrapper<>();
        templatePOQueryWrapper.eq("SITE_ID", siteId);
        templatePOQueryWrapper.eq("TYPE", "PC");
        templatePOQueryWrapper.eq("IS_USE",1);
        List<WebsiteTemplatePO> templatePOList = templateService.list(templatePOQueryWrapper);
        if (templatePOList == null || templatePOList.isEmpty()) {
            return R.success().data(templateTreeListVO);
        } else {
            ArrayList<HtmlTemplateTreeItemVO> templateTreeItemVOList = new ArrayList<>();
            WebsiteTemplatePO templatePO = templatePOList.get(0);
            // 遍历每个模板id并获取其对应的模板树
            HtmlTemplateTreeListVO treeListByTemplateId = localFileService.getHtmlFileTreeListByTemplateId(templatePO.getId());
            // treeListByTemplateId 中只有一个模板id对应的树，所以取出其集合
            List<HtmlTemplateTreeItemVO> treeList = treeListByTemplateId.getTreeList();

            HtmlTemplateTreeItemVO templateTreeItemVO = treeList.get(0);
            // 将vo添加到集合中
            templateTreeItemVOList.add(templateTreeItemVO);
            // 集合设置给封装对象
            templateTreeListVO.setTreeList(templateTreeItemVOList);
            templateTreeListVO.setTemplateId(templatePO.getId());
        }

        return R.success().data(templateTreeListVO);
    }

    @ApiOperation(value = "根据站点id获取默认H5模板", notes = "根据站点id获取默认H5模板")
    @GetMapping("/load-h5-template-tree-by-site-id")
    public R<HtmlTemplateTreeListVO> loadH5TemplateTreeBySiteId(@ApiParam(value = "站点id", required = true, example = "12312313123") @RequestParam(required = false) Long siteId) {

        // 校验id
        if (null == siteId || !ValidateUtil.Number(siteId) || siteId <= 0) return R.failureRequestParam().msg("站点id输入有误");

        // 返回值
        HtmlTemplateTreeListVO templateTreeListVO = new HtmlTemplateTreeListVO();

        // 根据站点id 查询pc类型的并且被是被使用的模板
        QueryWrapper<WebsiteTemplatePO> templatePOQueryWrapper = new QueryWrapper<>();
        templatePOQueryWrapper.eq("SITE_ID", siteId);
        templatePOQueryWrapper.eq("TYPE", "H5");
        templatePOQueryWrapper.eq("IS_USE",1);
        List<WebsiteTemplatePO> templatePOList = templateService.list(templatePOQueryWrapper);
        if (templatePOList == null || templatePOList.isEmpty()) {
            return R.success().data(templateTreeListVO);
        } else {
            ArrayList<HtmlTemplateTreeItemVO> templateTreeItemVOList = new ArrayList<>();
            WebsiteTemplatePO templatePO = templatePOList.get(0);
            // 遍历每个模板id并获取其对应的模板树
            HtmlTemplateTreeListVO treeListByTemplateId = localFileService.getHtmlFileTreeListByTemplateId(templatePO.getId());
            // treeListByTemplateId 中只有一个模板id对应的树，所以取出其集合
            List<HtmlTemplateTreeItemVO> treeList = treeListByTemplateId.getTreeList();

            HtmlTemplateTreeItemVO templateTreeItemVO = treeList.get(0);
            // 将vo添加到集合中
            templateTreeItemVOList.add(templateTreeItemVO);
            // 集合设置给封装对象
            templateTreeListVO.setTreeList(templateTreeItemVOList);
            templateTreeListVO.setTemplateId(templatePO.getId());
        }

        return R.success().data(templateTreeListVO);
    }

    @SitePermission({DELETE})
    @ApiOperation(value = "根据模板id删除模板", notes = "根据模板id删除模板")
    @DeleteMapping("/delete-template-by-templateId")
    public R deleteTemplateByTemplateId(@ApiParam(value = "模板id", required = true, example = "12312313123") @RequestParam(required = false) Long templateId,
                                        @ApiParam(value = "站点id", required = true, example = "12312313123") @RequestParam(required = false) Long siteId) {
        if (null == templateId || StringUtils.isEmpty(String.valueOf(templateId))) return R.failureRequestParam().msg("模板id不能为空");
        if (null == siteId || StringUtils.isEmpty(String.valueOf(siteId))) return R.failureRequestParam().msg("模板id不能为空");

//        siteId = 1447101029687484417L;
//        templateId = 1448128774445936642L;

        WebsiteTemplatePO templatePO = templateService.getById(templateId);

        // 根路径为：配置的根路径+站点id+template+模板编码
        String templateRootPath;
        templateRootPath = resourceStorageRootPath + File.separator + siteId + File.separator +
                "template" + File.separator + templatePO.getCode();

        File file = FileUtil.file(templateRootPath);
        // 删除模板文件
        if (file.exists()) {
            FileUtil.del(file);
            templateService.removeById(templateId);
            System.out.println("success!");
        } else {
            return R.failure().msg("模板文件不存在");
        }
        return R.success();
    }


    @SitePermission({DELETE})
    @ApiOperation(value = "根据模板id删除模板", notes = "根据模板id删除模板")
    @DeleteMapping("/delete-template-by-templateIds")
    public R deleteTemplateByTemplateId(@ApiParam(value = "模板ids", required = true, example = "12312313123") @RequestParam(required = false) String ids,
                                        @ApiParam(value = "站点id", required = true, example = "12312313123") @RequestParam(required = false) Long siteId) {
        if (null == ids || StringUtils.isEmpty(String.valueOf(ids))) return R.failureRequestParam().msg("模板ids不能为空");
        if (null == siteId || StringUtils.isEmpty(String.valueOf(siteId))) return R.failureRequestParam().msg("站点id不能为空");

        String[] split = ids.split(",");

        ArrayList<Long> templateIdList = new ArrayList<>();
        for (String s : split) {
            templateIdList.add(Long.parseLong(s));
        }
        List<WebsiteTemplatePO> websiteTemplatePOS = templateService.listByIds(templateIdList);

        for (WebsiteTemplatePO templatePO : websiteTemplatePOS) {
            // 根路径为：配置的根路径+站点id+template+模板编码
            String templateRootPath;
            templateRootPath = resourceStorageRootPath + File.separator + siteId + File.separator +
                    "template" + File.separator + templatePO.getCode();
            File file = FileUtil.file(templateRootPath);
            // 删除模板文件
            if (file.exists()) {
                FileUtil.del(file);
                templateService.removeById(templatePO.getId());
                System.out.println("success!");
            } else {
                return R.failure().msg(templatePO.getName() + ":模板文件不存在");
            }
        }
        return R.success();
    }




}
